package com.siae.config;


import com.siae.exce.BizException;
import com.siae.pojo.vo.Result;
import com.siae.utils.BizCode;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Map<String,String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        Map<String,String> map = new HashMap<>();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        }
        return Result.fail(BizCode.DATA_VALID_ERROR,map);
    }
    @ExceptionHandler(BizException.class)
    public Result handleException(BizException e){
        return Result.fail(e.getCode(),e.getMessage());
    }
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        return Result.fail(BizCode.FAIL,e.getMessage());
    }
}
